package com.example.baselibrary.commonutil;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

public class DensityModifier {

    private static final String TAG = "DensityModifier";

    public static final int STANDARD_WIDTH = 0;
    public static final int STANDARD_HEIGHT = 1;

    private static float sNoncompatDensity;
    private static float sNocompatScaledDensity;

    /**
     * 修改density
     * @param activity 需要修改density的Activity
     * @param application
     * @param length UI设计图的标准屏幕宽度,单位为dp
     */
    public static void setDensity(Activity activity, final Application application, int length) {
        setDensity(activity, application, length, STANDARD_WIDTH);
    }

    /**
     * 修改density
     * @param activity 需要修改density的Activity
     * @param length UI设计图的标准屏幕宽度,单位为dp
     * @param application
     * @param standardType 以宽还是高为标准
     */
    public static void setDensity(Activity activity, final Application application, int length, int standardType) {
        final DisplayMetrics appDisplayMetrics = activity.getResources().getDisplayMetrics();

        if (sNoncompatDensity == 0) {
            sNoncompatDensity = appDisplayMetrics.density;
            sNocompatScaledDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sNocompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }

        final float targetDensity;
        if (standardType == STANDARD_WIDTH) {
            targetDensity = (float) appDisplayMetrics.widthPixels / length;
        } else {
            targetDensity = (float) appDisplayMetrics.heightPixels / length;
        }
        final float targetScaleDensity = targetDensity * (sNocompatScaledDensity / sNoncompatDensity);
        final int targetDensityDpi = (int) (targetDensity * 160);

        appDisplayMetrics.density = targetDensity;
        appDisplayMetrics.scaledDensity = targetScaleDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;

        final DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;
        activityDisplayMetrics.scaledDensity = targetScaleDensity;

    }
}
